package com.example.j2eeapp.services.impl;

import javax.faces.application.FacesMessage;
import javax.faces.context.FacesContext;

import org.springframework.security.authentication.AuthenticationManager;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.core.context.SecurityContextHolder;

import com.example.j2eeapp.domain.UserEntity;
import com.example.j2eeapp.services.UserAuthenticationProviderService;


/**
 * Provides processing service to set user authentication session
 * 
 * @author cipherCata
 *
 */
public class UserAuthenticationProviderServiceImpl implements UserAuthenticationProviderService {

	//dependcy Injection
	/*Inject the setter authenticationManager with the authenticationManager 
	from security-config.xml which will lead to ref the UserDao class and 
	spring security classes to do the authentications through the chain of dependency*/
	private AuthenticationManager authenticationManager;
	
	/**
	 * 
	 * Process user authentication
	 * 
	 * @param user
	 * @return
	 */
	//create a method called processUserAuthentication and give it a user of type UserEntity to retrieve the current user/info/context
	public boolean processUserAuthentication(UserEntity user) {
		try {
			//create a var called request(encapsulate getPassword()) of type Authentication and assign it a password token to the password
			Authentication request = new UsernamePasswordAuthenticationToken(
					user.getUserName(), user.getPassword());
			//create a var called result and assign it the authenticated request.
			Authentication result = authenticationManager.authenticate(request);
			
			//get the context and set the authentication of the result.
			SecurityContextHolder.getContext().setAuthentication(result);
			return true;
			
		} catch (AuthenticationException e) {
			//get the current instance and add the message from UsernameNotFoundException which thrown from the class UserServiceImpl
			FacesContext.getCurrentInstance().addMessage(null, new FacesMessage(FacesMessage.SEVERITY_ERROR, e.getMessage(), "Not Excepted"));
			
			return false;
		}
		
		
	}

	public AuthenticationManager getAuthenticationManager() {
		return authenticationManager;
	}

	public void setAuthenticationManager(AuthenticationManager authenticationManager) {
		this.authenticationManager = authenticationManager;
	}

}
